package org.tis.tools.senior.module.developer.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.tis.tools.senior.module.developer.controller.request.DeliveryListAndDeliveryAddRequest;
import org.tis.tools.senior.module.developer.controller.request.DeliveryListSelectRequest;
import org.tis.tools.senior.module.developer.controller.request.DeliveryListSuperadditionRequest;
import org.tis.tools.senior.module.developer.controller.request.DeliveryProfileRequest;
import org.tis.tools.senior.module.developer.dao.SDeliveryListMapper;
import org.tis.tools.senior.module.developer.entity.*;
import org.tis.tools.senior.module.developer.entity.enums.*;
import org.tis.tools.senior.module.developer.entity.vo.DeliveryListStashListDetail;
import org.tis.tools.senior.module.developer.entity.vo.DeliveryProjectDetail;
import org.tis.tools.senior.module.developer.entity.vo.FileUsedList;
import org.tis.tools.senior.module.developer.entity.vo.SvnFile;
import org.tis.tools.senior.module.developer.exception.DeveloperException;
import org.tis.tools.senior.module.developer.service.*;
import org.tis.tools.senior.module.developer.util.DeveloperUtils;
import org.tmatesoft.svn.core.SVNException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * sDeliveryList的Service接口实现类
 *
 * @author lijh
 * @date 2018/06/20
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SDeliveryListServiceImpl extends ServiceImpl<SDeliveryListMapper, SDeliveryList> implements ISDeliveryListService {


    @Autowired
    private ISSvnKitService svnKitService;

    @Autowired
    private ISProjectService projectService;

    @Autowired
    private ISBranchService branchService;

    @Autowired
    private ISDeliveryService deliveryService;

    @Autowired
    private ISBranchMappingService branchMappingService;

    @Autowired
    private ISStandardListService standardListService;

    @Autowired
    private ISProfilesService profilesService;

    @Autowired
    private ISWorkitemService workitemService;

    @Autowired
    private ISCheckService checkService;

    @Autowired
    private ISStashListService stashListService;

    @Autowired
    private ISRollbackService rollbackService;

    @Autowired
    private ISRepealService repealService;

    @Override
    public DeliveryListStashListDetail assembleDelivery(String branchGuid) throws SVNException {

        SBranch branch = branchService.selectById(branchGuid);
        if (branch == null) {
            throw new DeveloperException("查询不到此分支！");
        }
        EntityWrapper<SBranchMapping> branchMappingEntityWrapper = new EntityWrapper<>();
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_GUID_BRANCH,branch.getGuid());
        List<SBranchMapping> branchMappings = branchMappingService.selectList(branchMappingEntityWrapper);
        if(branchMappings.size() != 1){
            throw new DeveloperException("查询不到此"+branchGuid+"关联的工作项！");
        }

        List<SvnFile> svnCommits = svnKitService.getBranchDiffStatus(
                    branch.getFullPath(), branch.getCurrVersion().toString());
        //查询所有的工程
        List<SProject> projectList = projectService.selectProjectAll();
        Map<String, SProject> projectMap = projectList.stream().
                collect(Collectors.toMap(SProject::getProjectName, p -> p));
        SWorkitem workitem = workitemService.selectById(branchMappings.get(0).getGuidOfWhats());
        //查询当前工作项的贮藏清单列表
        EntityWrapper<SStashList> stashEntityWrapper = new EntityWrapper<>();
        stashEntityWrapper.eq(SStashList.COLUMN_GUID_WORKITEM, workitem.getGuid());
        List<SStashList> sStashLists = stashListService.selectList(stashEntityWrapper);
        if (svnCommits.size() == 0 && sStashLists .size() == 0) {
            throw new DeveloperException("该清单已被整理或没有最新的提交记录!");
        }
        List<SDeliveryList> sdList = new ArrayList<>();
        if(svnCommits.size() > 0){
            Map<String, List<SvnFile>> commitMap = svnCommits.stream().collect(Collectors.groupingBy(SvnFile::getNodeType));
            Set<String> ecdSet = new HashSet<>();
            if (commitMap.get("dir") != null) {
                commitMap.get("dir").forEach(f -> {
                    String projectName = DeveloperUtils.getProjectName(f.getPath(),branch.getFullPath());
                    if (StringUtils.isNotBlank(projectName)) {
                        SProject project = projectMap.get(projectName);
                        if (project == null) {
                            throw new DeveloperException("基础参数中没有"+ projectName +"此工程，如要整理清单，请联系rct组创建此工程！");
                        }
                        JSONArray jsonArray = JSONArray.parseArray(project.getDeployConfig());
                        for (Object object : jsonArray) {
                            JSONObject jsonObject = JSONObject.parseObject(object.toString());
                            String exportType = jsonObject.getString("exportType");
                            if ("ecd".equals(exportType)) {
                                String module = DeveloperUtils.getModule(f.getPath(), branch.getFullPath());
                                if (StringUtils.isNoneBlank(module) && f.getType().equals(CommitType.ADDED) &&
                                        f.getPath().endsWith(module)) {
                                    String path = f.getPath();
                                    String subPath = path.substring(0, path.indexOf(path) + path.length());
                                    if (subPath.equals(f.getPath())) {
                                        ecdSet.add(projectName+"/"+module);
                                    }
                                }
                            }
                        }
                    }
                });
            }
            if (commitMap.get("file") != null) {
                commitMap.get("file").forEach(svnFile -> {
                    SDeliveryList sdl = new SDeliveryList();
                    sdl.setCommitType(svnFile.getType());
                    sdl.setFullPath(svnFile.getPath());
                    sdl.setFromType(DeliveryListFromType.BRANCH);
                    String programName = DeveloperUtils.getProgramName(svnFile.getPath());
                    sdl.setProgramName(programName);
                    String projectName = DeveloperUtils.getProjectName(svnFile.getPath(),branch.getFullPath());
                    SProject sProject = projectMap.get(projectName);
                    if (sProject == null) {
                        throw new DeveloperException("基础参数中没有"+ projectName +"此工程，如要整理清单，请联系rct组创建此工程！");
                    }
                    sdl.setPartOfProject(sProject.getProjectName());
                    String deployConfig = sProject.getDeployConfig();
                    if(ProjectType.IBS.equals(sProject.getProjectType())) {
                        String contriType = "";
                        try {
                            contriType = svnKitService.getPatchDeploy(sdl.getFullPath(),branch.getFullPath());
                        } catch (SVNException e) {
                            e.printStackTrace();
                        }
                        JSONArray jsonArray = JSONArray.parseArray(deployConfig);
                        //here  跳出循环的标记
                        here:
                        for (Object object : jsonArray) {
                            //解析json字符串获取导出类型和部署到那
                            JSONObject jsonObject = JSONObject.parseObject(object.toString());
                            String exportType = jsonObject.getString("exportType");
                            if (exportType.equals("ecd")) {
                                if (ecdSet.size() > 0) {
                                    for (String ecd : ecdSet) {
                                        if (svnFile.getPath().contains(ecd)) {
                                            sdl.setPatchType(exportType);
                                            sdl.setDeployWhere(DeliveryProjectDetail.
                                                    getDeployWhereBuildPackType(exportType,deployConfig,contriType));
                                            break here;
                                        }
                                    }
                                }
                            } else {
                                sdl.setPatchType(exportType);
                                sdl.setDeployWhere(DeliveryProjectDetail.
                                        getDeployWhereBuildPackType(exportType,deployConfig,contriType));
                            }
                        }
                    }else{
                        JSONArray jsonArray = JSONArray.parseArray(deployConfig);
                        String exportType = "";
                        for (Object object : jsonArray) {
                            JSONObject jsonObject = JSONObject.parseObject(object.toString());
                            if("".equals(exportType)){
                                exportType = jsonObject.getString("exportType");
                            }else{
                                exportType = exportType + "," + jsonObject.getString("exportType");
                            }
                        }
                        sdl.setPatchType(exportType);
                        sdl.setDeployWhere(DeliveryProjectDetail.generateDeployWhereString(exportType, deployConfig));
                    }
                    sdList.add(sdl);
                });
            }
        }
        //保存需要删除的贮藏清单代码
        List<SStashList> deletesStashList = new ArrayList<>();
        //保存需要删除整理的清单代码
        List<SDeliveryList> deleteDeliveryLists = new ArrayList<>();
        //保存需要修改整理的清单代码
        List<SDeliveryList> updateDeliveryLists = new ArrayList<>();

        List<SDeliveryList> stashLists = new ArrayList<>();
        if(sStashLists.size() > 0){
            //遍历整理的清单代码
            for (SDeliveryList deliveryList:sdList){
                //遍历贮藏的清单代码
                for(SStashList stashList:sStashLists){
                    //判断贮藏清单和整理的清单的文件是否相同
                    if((stashList.getFullPath()).equals(deliveryList.getFullPath())){
                        //判断贮藏清单和整理的清单的文件提交类型是否相同
                        if(!deliveryList.getCommitType().equals(stashList.getCommitType())){
                            // 原-现—终 (修改类型的变化)
                            // D  A  M
                            // M  A  M 理论上不出现，如果发生抛出异常
                            // A  D  X 移除
                            // M  D  D
                            // A  M  A 不处理
                            // D  M  M 理论上不出现，如果发生抛出异常// D  A  M
                            // A  A  A 不处理
                            // M  M  M 不处理
                            // D  D  D 不处理
                            if(deliveryList.getCommitType().equals(CommitType.ADDED) &&
                                    stashList.getCommitType().equals(CommitType.DELETED)){
                                deliveryList.setCommitType(CommitType.MODIFIED);
                                updateDeliveryLists.add(deliveryList);
                            }else if(deliveryList.getCommitType().equals(CommitType.DELETED) &&
                                    stashList.getCommitType().equals(CommitType.ADDED)){
                                deleteDeliveryLists.add(deliveryList);
                            }else if(deliveryList.getCommitType().equals(CommitType.MODIFIED) &&
                                    stashList.getCommitType().equals(CommitType.ADDED)){
                                deliveryList.setCommitType(CommitType.ADDED);
                                updateDeliveryLists.add(deliveryList);
                            }else if(deliveryList.getCommitType().equals(CommitType.DELETED) &&
                                    stashList.getCommitType().equals(CommitType.MODIFIED)){

                            } else {
                                throw new DeveloperException("整理的清单与贮藏的清单提交类型不符合规则！");
                            }
                        }
                        //保存与整理清单相同的文件
                        deletesStashList.add(stashList);
                        //跳出到本次循环的标识
                        break;
                    }
                }
            }
            if(deletesStashList.size() > 0){
                //移除贮藏与整理出的清单相同的文件
                sStashLists.removeAll(deletesStashList);
                //同时删除贮藏清单与整理清单相同的文件代码
                stashListService.deleteBatchIds(deletesStashList.stream().map(
                        SStashList::getGuid).collect(Collectors.toList()));
            }
            if(sStashLists.size() > 0){
                //将SStashList对象值copy到SDeliveryList对象中
                sStashLists.forEach(stash ->{
                    SDeliveryList delivery = new SDeliveryList();
                    BeanUtils.copyProperties(stash,delivery);
                    stashLists.add(delivery);
                });
            }

        }
        //移除相同文件：整理出的清单提交类型为删除，贮藏清单为新增的相同文件。
        if(sdList. size() > 0){
            sdList.removeAll(deleteDeliveryLists);
        }
        List<SDeliveryList> deliveryLists = new ArrayList<>();
        //遍历移除相同文件的整理出的清单集合
        for(SDeliveryList sd:sdList){
            //遍历整理出的清单需要修改的文件
            for(SDeliveryList sdl:updateDeliveryLists){
                if(sdl.getFullPath().equals(sd.getFullPath())){
                    sd.setCommitType(sdl.getCommitType());
                    break;
                }
            }
            deliveryLists.add(sd);
        }
        DeliveryListStashListDetail detail = new DeliveryListStashListDetail();
        List<DeliveryProjectDetail> deliveryDetail = null;
        //将整理出来的清单按工程分组
        if(deliveryLists.size() > 0){
            deliveryDetail = DeliveryProjectDetail.getDeliveryListDetail(deliveryLists, projectList);
        }
        detail.setDeliveryDetail(deliveryDetail);
        List<DeliveryProjectDetail> stashDetail = null;
        //将贮藏清单按工程分组
        if(stashLists.size() > 0) {
            stashDetail = DeliveryProjectDetail.getDeliveryListDetail(stashLists, projectList);
        }
        detail.setStashDetail(stashDetail);
        return detail;
    }

    @Override
    public List<SDelivery> addDeliveryList(DeliveryListAndDeliveryAddRequest request, String userId)
                throws SVNException, ParseException {
        if(request.getDliveryAddRequest().getProfiles().size() == 0){
            throw new DeveloperException("请选择要投放的环境及打包窗口再投放！");
        }
        //判断投放时间及投放窗口是否合理
        Date date = new Date();
        SimpleDateFormat ymdFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat hmFormat = new SimpleDateFormat("HH:mm");
        for(DeliveryProfileRequest profile:request.getDliveryAddRequest().getProfiles()){
            if (ymdFormat.format(profile.getDeliveryTime()).equals(ymdFormat.format(date))){
                //投放窗口的时间戳
                long time1 = hmFormat.parse(profile.getPackTiming()).getTime();
                //当前时间的时间戳
                long time2 = hmFormat.parse(hmFormat.format(date)).getTime();
                if(time2 > time1){
                    throw new DeveloperException("你投放的窗口已经过期，请选择下一个窗口投放！");
                }
            }else{
                //将投放时间转成时间戳
                long deliverTime1 = ymdFormat.parse(ymdFormat.format(profile.getDeliveryTime())).getTime();
                //当前时间的时间戳
                long time2 = ymdFormat.parse(ymdFormat.format(profile.getDeliveryTime())).getTime();
                if(time2 > deliverTime1){
                    throw new DeveloperException("你选择的投放日期已是过去日期，请重新投放时间！");
                }
            }
        }

        //查询所有工程
        Map<String, SProject> projectMap = projectService.selectProjectAll().stream().
                collect(Collectors.toMap(SProject::getProjectName, p -> p));
        //获取已成功投放的投放申请
        EntityWrapper<SDelivery> deliveryEntityWrapper = new EntityWrapper<>();
        deliveryEntityWrapper.eq(SDelivery.COLUMN_GUID_WORKITEM,request.getGuidWorkitem());
        deliveryEntityWrapper.eq(SDelivery.COLUMN_DELIVERY_RESULT,DeliveryResult.DELIVERED);
        List<SDelivery> deliverys = deliveryService.selectList(deliveryEntityWrapper);
        if(deliverys.size() == 0 && request.getDeliveryList().size() == 0){
            throw new DeveloperException("没有要投放的代码！");
        }

        //获取工作项已成功投放申请的运行环境guid
        Set<Integer> achieveProfileGuid = new HashSet<>();
        //保存此工作项成功投放并且开启的环境guid集合
        List<Integer> guidProfiles = new ArrayList<>();
        if(deliverys.size() > 0){
            for (SDelivery delivery:deliverys) {
                achieveProfileGuid.add(delivery.getGuidProfiles());
            }
            //获取选择投放并且开启的运行环境
            EntityWrapper<SProfiles> profilesEntityWrapper = new EntityWrapper<>();
            profilesEntityWrapper.in(SProfiles.COLUMN_GUID, achieveProfileGuid);
            profilesEntityWrapper.eq(SProfiles.COLUMN_IS_ALLOW_DELIVERY, IsAllowDelivery.ALLOW);
            List<SProfiles> profiles = profilesService.selectList(profilesEntityWrapper);

            guidProfiles = profiles.stream().map(SProfiles::getGuid).collect(Collectors.toList());

            //获取本次投放的环境guid集合
            List<Integer> nowGuidProfile = request.getDliveryAddRequest().getProfiles().stream().
                    map(DeliveryProfileRequest::getGuidProfiles).collect(Collectors.toList());
            if(request.getDeliveryList().size() > 0){
                if(!nowGuidProfile.containsAll(guidProfiles)){
                    throw new DeveloperException("本次投放选择的环境必须包含此工作项已投放的环境！");
                }
            }else{
                if(nowGuidProfile.contains(guidProfiles)){
                    throw new DeveloperException("未选择代码清单只能向新环境投放！");
                }
            }
        }

        EntityWrapper<SRollback> rollbackEntityWrapper = new EntityWrapper<>();
        rollbackEntityWrapper.eq(SRollback.COLUMN_ROLLBACK_STATUS, RollbackStatus.UNDERWAY)
                                .eq(SRollback.COLUMN_GUID_WORKITEM, request.getGuidWorkitem());
        List<SRollback> rollbacks = rollbackService.selectList(rollbackEntityWrapper);
        if(rollbacks.size() > 0){
            throw new DeveloperException("此工作项有回退申请未完成回退，请完成完后再投放！");
        }
        EntityWrapper<SRepeal> repealEntityWrapper = new EntityWrapper<>();
        repealEntityWrapper.eq(SRepeal.COLUMN_REPEAL_STATUS, RepealStatus.MODIFIED)
                .eq(SRepeal.COLUMN_GUID_WORKITEM, request.getGuidWorkitem());
        List<SRepeal> repeals = repealService.selectList(repealEntityWrapper);
        if(repeals.size() > 0){
            throw new DeveloperException("此工作项有延期申请未完成，请完成完后再投放！");
        }

        //判断是否是新投放
        EntityWrapper<SDelivery> deliverysEntityWrapper = new EntityWrapper<>();
        deliverysEntityWrapper.eq(SDelivery.COLUMN_GUID_WORKITEM,request.getGuidWorkitem());
        deliverysEntityWrapper.eq(SDelivery.COLUMN_DELIVERY_RESULT, DeliveryResult.APPLYING);
        deliverysEntityWrapper.eq(SDelivery.COLUMN_APPLY_TYPE, ApplyType.DELIVERY);
        List<SDelivery> sDeliveries = deliveryService.selectList(deliverysEntityWrapper);
        if(sDeliveries.size() > 0 && request.getDeliveryList().size() > 0){
            throw new DeveloperException("你有投放申请正在申请中，如要投放，请追加投放！");
        }
        //创建已选择的环境的投放申请中的运行环境guid集合
        List<Integer> choiceProfileGuid = request.getDliveryAddRequest().getProfiles().stream().map(
                DeliveryProfileRequest::getGuidProfiles).collect(Collectors.toList());
        //集合添加核对中及核对成功状态，控制投放申请的环境是否可投放
        List<CheckStatus> checkStatuses = new ArrayList<>();
        checkStatuses.add(CheckStatus.WAIT);
        checkStatuses.add(CheckStatus.SUCCESS);
        //获取这个投放申请的运行环境是否有正在核对中
        EntityWrapper<SCheck> checkEntityWrapper = new EntityWrapper<>();
        int index = 0;
        for(DeliveryProfileRequest profileRequest:request.getDliveryAddRequest().getProfiles()){
            checkEntityWrapper.eq(SCheck.COLUMN_GUID_PROFILES, profileRequest.getGuidProfiles());
            checkEntityWrapper.in(SCheck.COLUMN_CHECK_STATUS, checkStatuses);
            checkEntityWrapper.eq(SCheck.COLUMN_PACK_TIMING, profileRequest.getPackTiming());
            checkEntityWrapper.eq("DATE_FORMAT(" + SCheck.COLUMN_DELIVERY_TIME + ", '%Y-%m-%d')",
                    new SimpleDateFormat("yyyy-MM-dd").format(profileRequest.getDeliveryTime()));
            index++;
            if(index != request.getDliveryAddRequest().getProfiles().size()){
                checkEntityWrapper.orNew();
            }
        }
        List<SCheck> checks = checkService.selectList(checkEntityWrapper);
        if(checks.size() > 0){
            throw new DeveloperException("你本次投放的环境窗口有申请正在核对中或已核对完成，请投放下一个窗口！");
        }

        //获取投放日期以及具体打包窗口是否已经完成投放
        EntityWrapper<SDelivery> deliveryWrapper = new EntityWrapper<>();
        int delIndex = 0;
        for (DeliveryProfileRequest profileRequest:request.getDliveryAddRequest().getProfiles()){
            deliveryWrapper.in(SDelivery.COLUMN_DELIVERY_RESULT,DeliveryResult.doneResult());
            deliveryWrapper.eq("DATE_FORMAT(" + SDelivery.COLUMN_DELIVERY_TIME + ", '%Y-%m-%d')",
                    new SimpleDateFormat("yyyy-MM-dd").format(profileRequest.getDeliveryTime()));
            deliveryWrapper.eq(SDelivery.COLUMN_PACK_TIMING,profileRequest.getPackTiming());
            deliveryWrapper.eq(SDelivery.COLUMN_GUID_PROFILES,profileRequest.getGuidProfiles());
            delIndex++;
            if(delIndex != request.getDliveryAddRequest().getProfiles().size()){
                deliveryWrapper.orNew();
            }
        }
        List<SDelivery> deliveries = deliveryService.selectList(deliveryWrapper);
        if(deliveries.size() > 0 && checks.size() > 0){
            throw new DeveloperException("你选择的投放环境对应的打包窗口已完成投放，请选择其他时间投放！");
        }
        //查询此工作项的投放申请按提交申请时间排序
        EntityWrapper<SDelivery> orderDeliveryEntityWrapper = new EntityWrapper<>();
        orderDeliveryEntityWrapper.eq(SDelivery.COLUMN_GUID_WORKITEM, request.getGuidWorkitem());
        orderDeliveryEntityWrapper.orderBy(SDelivery.COLUMN_APPLY_TIME, false);
        List<SDelivery> descDelivery = deliveryService.selectList(orderDeliveryEntityWrapper);

        //获取分支详情
        SBranch branch= branchService.selectById(request.getGuidBranch());
        //获取最后版本号
        int lastVersion = svnKitService.getLastRevision(branch.getFullPath());
        //新增投放申请列表
        List<SDelivery> deliveryList = new ArrayList<>();
        List<DeliveryProfileRequest> guidPro = request.getDliveryAddRequest().getProfiles();
        //获取当前提交的时间
        Date applyTime = new Date();
        //获取时间戳
        long batchNumber = applyTime.getTime();
        for (DeliveryProfileRequest req : guidPro) {
            for (Integer guidProfile:guidProfiles){
                if(req.getGuidProfiles().equals(guidProfile) && request.getDeliveryList().size() == 0){
                    throw new DeveloperException("没有新的提交清单，只能向新环境投放申请！");
                }
            }
            //组装投放申请
            SDelivery delivery = new SDelivery();
            delivery.setApplyAlias(req.getApplyAlias());
            delivery.setGuidWorkitem(request.getGuidWorkitem());
            if(profilesService.selectById(req.getGuidProfiles()) == null){
                throw new DeveloperException("投放的环境不存在，请重新选择环境！");
            }
            delivery.setGuidProfiles(req.getGuidProfiles());
            delivery.setDeliveryType(DeliveryType.GENERAL);
            delivery.setProposer(userId);
            delivery.setApplyTime(applyTime);
            delivery.setPackTiming(req.getPackTiming());
            delivery.setDeliveryTime(req.getDeliveryTime());
            delivery.setDeliveryResult(DeliveryResult.APPLYING);
            delivery.setApplyType(ApplyType.DELIVERY);
            delivery.setBeginVersion(branch.getLastVersion());
            delivery.setEndVersion(lastVersion);
            //将投放新环境的的申请批次号与上次投放申请中的申请保持一致
            if(sDeliveries.size() > 0){
                SDelivery sDelivery = sDeliveries.get(0);
                delivery.setBatchNumber(sDelivery.getBatchNumber());
            }else{
                delivery.setBatchNumber(String.valueOf(batchNumber));
            }
            deliveryList.add(delivery);
        }

        //批量添加投放申请
        deliveryService.insertBatch(deliveryList);
        //添加标准清单的集合
        List<SDeliveryList> standardlList = new ArrayList<>();
        //判断此工作项是否有成功投放的申请记录
        if (achieveProfileGuid.size() > 0) {
            //移除已成功投放运行环境的投放申请
            choiceProfileGuid.removeAll(achieveProfileGuid);
            if(choiceProfileGuid.size() > 0){
                //保存新投放代码清单的代码全路径
                List<String> fullPathList = request.getDeliveryList().stream().map(
                        SDeliveryList::getFullPath).collect(Collectors.toList());
                //获取工作项的标准清单记录
                EntityWrapper<SStandardList> standardListEntityWrapper = new EntityWrapper<>();
                standardListEntityWrapper.eq(SStandardList.COLUMN_GUID_WORKITEM,request.getGuidWorkitem());
                //查询标准清单与本次投放清单不同的fullPath代码
                if(fullPathList.size() > 0){
                    standardListEntityWrapper.notIn(SStandardList.COLUMN_FULL_PATH,fullPathList);
                }
                List<SStandardList> sStandardLists = standardListService.selectList(standardListEntityWrapper);
                if(sStandardLists.size() > 0){
                    //此次的投放申请选择的环境过滤掉已成功投放的环境后的投放申请集合
                    List<SDelivery> sDeliveries1 = deliveryList.stream().filter(sDelivery -> choiceProfileGuid.contains(
                            sDelivery.getGuidProfiles())).collect(Collectors.toList());
                    //组装并新增标准清单内容
                    for(SDelivery delivery:sDeliveries1){
                        for(SStandardList sStandard:sStandardLists){
                            SDeliveryList sdl = new SDeliveryList();
                            BeanUtils.copyProperties(sStandard,sdl);
                            sdl.setGuidDelivery(delivery.getGuid());
                            sdl.setGuid(null);
                            sdl.setFromType(DeliveryListFromType.STANDARD);
                            standardlList.add(sdl);
                        }
                    }
                    if(standardlList.size() > 0){
                        insertBatch(standardlList);
                    }

                }
            }
        }
        List<SDeliveryList> deliveryLists = new ArrayList<>();
        //新增对应的投放申请的代码清单
        if(request.getDeliveryList().size() > 0) {
            for (SDelivery sDelivery : deliveryList) {
                //组装投产代码清单
                for (SDeliveryList dlar : request.getDeliveryList()) {
                    SDeliveryList sDeliveryList = new SDeliveryList();
                    BeanUtils.copyProperties(dlar, sDeliveryList);
                    for (SDeliveryList standardList : standardlList) {
                        //判断标准清单里是否有代码清单导出为ECD
                        if (PatchType.ECD.equals(standardList.getPatchType())) {
                            //获取构建包名
                            String moudle = DeveloperUtils.getModulePath(standardList.getFullPath(),
                                        standardList.getPartOfProject());
                            /*
                                如果标准清单的工程模块导出为ecd，这次投放的代码清单也是标准清单模块下的文件，那么将
                                这个投放代码的导出变更标准清单的导出类型
                             */
                            if (dlar.getFullPath().contains(moudle) && PatchType.EPD.equals(dlar.getPatchType())) {
                                sDeliveryList.setPatchType(standardList.getPatchType());
                                break;
                            }
                        }
                    }
                    sDeliveryList.setGuidDelivery(sDelivery.getGuid());
                    //判断投放的代码是否是config工程
                    if (projectMap.get(dlar.getPartOfProject()).getProjectType().equals(ProjectType.SPECIAL)) {
                        //组装json格式保存
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put(dlar.getPatchType(), dlar.getDeployWhere());
                        sDeliveryList.setDeployWhere(jsonObject.toString());
                    } else {
                        //解析不是config工程的部署类型，然后保存
                        sDeliveryList.setDeployWhere(DeliveryProjectDetail.generateDeployWhereString(
                                dlar.getPatchType(), projectMap.get(dlar.getPartOfProject()).getDeployConfig()));
                    }
                    deliveryLists.add(sDeliveryList);
                }
            }
            //批量添加此次投放的代码清单
            insertBatch(deliveryLists);
            //记录分支临时版本号
            branchService.recordBranchTempRevision(branch.getGuid(),lastVersion);
        }
        if(descDelivery.size() > 0){
            //获取所有排过序的投放申请中最近当前时间的一条投放申请
            SDelivery sDelivery = descDelivery.get(0);
            //获取上次同一批次的投放申请
            List<SDelivery> lateDelivery = descDelivery.stream().filter(delivery ->
                    sDelivery.getBatchNumber().equals(delivery.getBatchNumber())).collect(Collectors.toList());
            //获取上次投放申请中核对失败的申请
            List<SDelivery> lowDelivery = new ArrayList<>();
            for(SDelivery sd:lateDelivery){
                if(sd.getDeliveryResult().equals(DeliveryResult.FAILED)){
                    lowDelivery.add(sd);
                }
            }
            List<SDeliveryList> fixecDeliveryList = new ArrayList<>();
            //判断上次投放申请投放的条数等于核对失败的条数，不做处理
            if(lowDelivery.size() != lateDelivery.size()){
                for (SDelivery lowDeli:lowDelivery){
                    //循环本次投放的环境申请
                    for (SDelivery delivery:deliveryList){
                        if(lowDeli.getGuidProfiles().equals(delivery.getGuidProfiles())){
                            //获取此失败投放申请的投放代码清单
                            EntityWrapper<SDeliveryList> deliveryListEntityWrapper = new EntityWrapper<>();
                            deliveryListEntityWrapper.eq(SDeliveryList.COLUMN_GUID_DELIVERY, lowDeli.getGuid());
                            List<SDeliveryList> sDeliveryLists = selectList(deliveryListEntityWrapper);
                            //获取此次投放申请的代码清单全路径
                            List<String> fullPath = request.getDeliveryList().stream().
                                    map(SDeliveryList::getFullPath).collect(Collectors.toList());

                            List<SDeliveryList> deliverysList = sDeliveryLists.stream().filter(deliverieLists ->
                                    !fullPath.contains(deliverieLists.getFullPath())).collect(Collectors.toList());
                            //过滤核对失败与标准清单相同的代码清单
                            here:
                            for (SDeliveryList sDeliveryList:deliverysList){
                                for (SDeliveryList standard:standardlList){
                                    if(sDeliveryList.getFullPath().equals(standard.getFullPath())){
                                        continue here;
                                    }
                                }
                                sDeliveryList.setGuidDelivery(delivery.getGuid());
                                sDeliveryList.setFromType(DeliveryListFromType.FIXED);
                                fixecDeliveryList.add(sDeliveryList);
                            }
                        }
                    }
                }
                //将失败的投放申请代码清单再次投放
                if(fixecDeliveryList.size() > 0){
                    insertBatch(fixecDeliveryList);
                }
            }
        }
        //贮藏清单逻辑处理
        insertStashList(request.getGuidWorkitem(),  request.getStashList(), deliveryLists);

        return deliveryList;
    }

    @Override
    public List<SDeliveryList> selectDeliveryListExcel(List<Integer> guidDelivery) {

        List<SDelivery> deliveries = deliveryService.selectBatchIds(guidDelivery);
        if(deliveries.size() == 0){
            throw new DeveloperException("没有找到对应的投放申请！");
        }

        List<SDeliveryList> deliveryLists = new ArrayList<>();
        //获取申请中的工作项guid
        List<Integer> guidWorkitem = deliveries.stream().map(SDelivery::getGuidWorkitem).collect(Collectors.toList());
        Set<Integer> guidWork = new HashSet<>();
        //过滤相同的工作项guid
        guidWork.addAll(guidWorkitem);
        for(Integer guid:guidWork){

            List<SDelivery> sDeliveries = deliveries.stream().filter(deliverie ->
                        guid.equals(deliverie.getGuidWorkitem())).collect(Collectors.toList());
            //获取此申请的代码明细
            EntityWrapper<SDeliveryList> deliveryListEntityWrapper = new EntityWrapper<>();
            deliveryListEntityWrapper.in(SDeliveryList.COLUMN_GUID_DELIVERY,
                        sDeliveries.stream().map(SDelivery::getGuid).collect(Collectors.toList()));
            deliveryListEntityWrapper.ne(SDeliveryList.COLUMN_COMMIT_TYPE, CommitType.DELETED.getValue().toString());
            List<SDeliveryList> sdlList = selectList(deliveryListEntityWrapper);
            //获取此申请中工作项关联分支信息
            EntityWrapper<SBranchMapping> branchMappingEntityWrapper = new EntityWrapper<>();
            branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_GUID_OF_WHATS,guid);
            branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_FOR_WHAT, BranchForWhat.WORKITEM);
            List<SBranchMapping> branchMappings = branchMappingService.selectList(branchMappingEntityWrapper);

            SBranch branch = branchService.selectById(branchMappings.get(0).getGuidBranch());
            //导出的数据处理
            deliveryLists.addAll(disposeExportExcel(sdlList, branch.getFullPath()));
        }

        if(deliveryLists.size() == 0){
            throw new DeveloperException("此投放申请没有要导出的代码清单！");
        }
        return deliveryLists;
    }

    @Override
    public List<SDelivery> addToDeliveryList(DeliveryListSuperadditionRequest request) throws SVNException {

        if(request.getDeliveryList().size() == 0){
            throw new DeveloperException("请选择需要追加的投放代码清单！");
        }
        if(request.getGuidDelivery().size() == 0){
            throw new DeveloperException("请选择需要追加的投放申请！");
        }
        List<SDelivery> deliveries = deliveryService.selectBatchIds(request.getGuidDelivery());
        //获取同一批次的投放申请
        EntityWrapper<SDelivery> deliverysEntityWrapper = new EntityWrapper<>();
        deliverysEntityWrapper.eq(SDelivery.COLUMN_BATCH_NUMBER, deliveries.get(0).getBatchNumber());
        List<SDelivery> delis = deliveryService.selectList(deliverysEntityWrapper);
        if(delis.size() != request.getGuidDelivery().size()){
            throw new DeveloperException("请选择所有投放的申请进行追加投放！");
        }
        for (SDelivery delivery:delis){
            if(!delivery.getDeliveryResult().equals(DeliveryResult.APPLYING)){
                throw new DeveloperException("此工作项上次投放得申请正在处理或已处理完成，不允许追加！");
            }
        }
        EntityWrapper<SBranchMapping> branchMappingEntityWrapper = new EntityWrapper<>();
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_FOR_WHAT, BranchForWhat.WORKITEM);
        branchMappingEntityWrapper.eq(SBranchMapping.COLUMN_GUID_OF_WHATS,request.getGuidWorkitem());
        List<SBranchMapping> branchMappings = branchMappingService.selectList(branchMappingEntityWrapper);
        if(branchMappings.size() == 0){
            throw new DeveloperException("此工作项没有分支信息或者已被取消关联！");
        }
        //查询所有工程
        Map<String, SProject> projectMap = projectService.selectProjectAll().stream().
                collect(Collectors.toMap(SProject::getProjectName, p -> p));
        //获取追加申请前的代码清单
        EntityWrapper<SDeliveryList> sDeliveryListEntityWrapper = new EntityWrapper<>();
        sDeliveryListEntityWrapper.in(SDeliveryList.COLUMN_GUID_DELIVERY, request.getGuidDelivery());
        List<SDeliveryList> deliveryLists = selectList(sDeliveryListEntityWrapper);

        // 接受需要新增或修改的投放清单
        List<SDeliveryList> insertDelievryList = new ArrayList<>();
        // 移除原清单的提交类型是新增，追加清单是删除的清单文件
        List<SDeliveryList> removeDelivery = new ArrayList<>();
        //删除与追加清单相同的代码文件
        List<SDeliveryList> deletes = new ArrayList<>();
        for (Integer guidDelivery:request.getGuidDelivery()){
            for (SDeliveryList deliveryList:request.getDeliveryList()){
                SDeliveryList sDeliveryList = new SDeliveryList();
                BeanUtils.copyProperties(deliveryList,sDeliveryList);
                for(SDeliveryList dl:deliveryLists){
                    //判断文件是否是相同的
                    if(guidDelivery.equals(dl.getGuidDelivery()) &&
                            deliveryList.getFullPath().equals(dl.getFullPath())){
                        //保存与追加清单相同的文件
                        deletes.add(dl);
                        if(!deliveryList.getCommitType().equals(dl.getCommitType())){
                            // 原-现—终 (修改类型的变化)
                            // D  A  M
                            // M  A  M 理论上不出现，如果发生抛出异常
                            // A  D  X 移除
                            // M  D  D
                            // A  M  A 不处理
                            // D  M  M 理论上不出现，如果发生抛出异常// D  A  M
                            // A  A  A 不处理
                            // M  M  M 不处理
                            // D  D  D 不处理
                            if (dl.getCommitType().equals(CommitType.DELETED) &&
                                    deliveryList.getCommitType().equals(CommitType.ADDED)) {
                                sDeliveryList.setCommitType(CommitType.MODIFIED);
                            }  else if (dl.getCommitType().equals(CommitType.ADDED) &&
                                    deliveryList.getCommitType().equals(CommitType.DELETED)) {
                                removeDelivery.add(deliveryList);
                            } else if (dl.getCommitType().equals(CommitType.MODIFIED) &&
                                    deliveryList.getCommitType().equals(CommitType.DELETED)) {
                                sDeliveryList.setCommitType(CommitType.DELETED);
                            } else if (dl.getCommitType().equals(CommitType.ADDED) &&
                                    deliveryList.getCommitType().equals(CommitType.MODIFIED)) {
                                sDeliveryList.setCommitType(CommitType.ADDED);
                            } else {
                                throw new DeveloperException("追加投放发生了预料之外的异常！");
                            }
                        }
                        break;
                    }
                }
                sDeliveryList.setGuid(null);
                sDeliveryList.setGuidDelivery(guidDelivery);
                sDeliveryList.setDeployWhere(DeliveryProjectDetail.generateDeployWhereString(
                        deliveryList.getPatchType(), projectMap.get(deliveryList.getPartOfProject()).getDeployConfig()));
                insertDelievryList.add(sDeliveryList);
            }
        }
        if(insertDelievryList.size() > 0){
            //移除原清单的提交类型是新增，追加清单是删除的清单文件
            insertDelievryList.removeAll(removeDelivery);
            //批量新增这次追加的投放申请
            insertBatch(insertDelievryList);
        }
        if(deletes.size() > 0){
            //删除原清单中与这次追加相同的清单文件
            deleteBatchIds(deletes.stream().map(SDeliveryList::getGuid).collect(Collectors.toList()));
        }
        //获取分支对象信息
        SBranch branch = branchService.selectById(branchMappings.get(0).getGuidBranch());
        //获取最后版本号
        int lastVersion = svnKitService.getLastRevision(branch.getFullPath());
        //记录版本号
        branchService.recordBranchTempRevision(branch.getGuid(), lastVersion);
        //处理贮藏清单逻辑
        insertStashList(request.getGuidWorkitem(), request.getStashList(), request.getDeliveryList());
        for (SDelivery delivery:delis){
            delivery.setEndVersion(lastVersion);
        }
        //修改清单终止版本号
        deliveryService.updateBatchById(delis);
        //获取本次追加投放申请的详情
        EntityWrapper<SDelivery> deliveryEntityWrapper = new EntityWrapper<>();
        deliveryEntityWrapper.in(SDelivery.COLUMN_GUID,request.getGuidDelivery());
        List<SDelivery> deliverys = deliveryService.selectList(deliveryEntityWrapper);
        return deliverys;
    }

    private List<SDeliveryList> disposeExportExcel(List<SDeliveryList> sdlList, String branchPath){
        List<SDeliveryList> deliveryLists = new ArrayList<>();

        sdlList.stream().collect(Collectors.groupingBy(SDeliveryList::getPatchType)).forEach((p, list) -> {
            if (p.equals(PatchType.ECD.getValue())) {
                list.stream().collect(Collectors.groupingBy(SDeliveryList::getPartOfProject,
                    Collectors.groupingBy(dl -> DeveloperUtils.getModule(dl.getFullPath(), branchPath))))
                    .forEach((pj, m) -> m.forEach((module, l) -> {
                        // 导出ecd 的同工程清单
                        JSONObject jsonObject = JSONObject.parseObject(l.get(0).getDeployWhere());
                        String [] deployWhereSplit = jsonObject.getString(l.get(0).getPatchType()).split(",");

                        for (String deployWhere : deployWhereSplit) {
                            SDeliveryList sdl = new SDeliveryList();
                            sdl.setPatchType(l.get(0).getPatchType());
                            sdl.setDeployWhere(deployWhere);
                            sdl.setPartOfProject(pj);
                            sdl.setFullPath(DeveloperUtils.getEcdPath(l.get(0).getFullPath(), pj));
                            deliveryLists.add(sdl);
                        }
                    }));
            } else {
                for (SDeliveryList sd : list) {
                    JSONObject jsonObject = JSONObject.parseObject(sd.getDeployWhere());
                    String[] patchTypeSplit = sd.getPatchType().split(",");
                    for (String patchType : patchTypeSplit) {
                        String deployWhere = jsonObject.getString(patchType);
                        String[] deployWhereSplit = deployWhere.split(",");
                        for (String dw : deployWhereSplit) {
                            SDeliveryList sdl = new SDeliveryList();
                            sdl.setPatchType(patchType);
                            sdl.setDeployWhere(dw);
                            sdl.setPartOfProject(sd.getPartOfProject());
                            sdl.setFullPath(sd.getFullPath());
                            deliveryLists.add(sdl);
                        }
                    }

                }
            }
        });
        return deliveryLists;
    }

    /**
     * 贮藏清单逻辑
     * @param guidWorkitem
     * @param stashLists
     * @param delievryList
     */
    public void insertStashList(Integer guidWorkitem, List<SStashList> stashLists, List<SDeliveryList> delievryList){
        //查询此工作项的贮藏清单所有内容
        EntityWrapper<SStashList> stashListEntityWrapper = new EntityWrapper<>();
        stashListEntityWrapper.eq(SStashList.COLUMN_GUID_WORKITEM,guidWorkitem);
        List<SStashList> sStashLists = stashListService.selectList(stashListEntityWrapper);
        if(sStashLists.size() > 0){
            //获取未选择的代码路径集合
            List<String> noChooesStash = stashLists.stream().
                    map(SStashList::getFullPath).collect(Collectors.toList());
            //过滤出贮藏清单中本次有选择贮藏的代码清单集合
            List<SStashList> chooesStash = sStashLists.stream().filter(sStashList -> !noChooesStash.
                    contains(sStashList.getFullPath())).collect(Collectors.toList());
            //获取本次申请选择了贮藏清单的代码集合
            List<SDeliveryList> sDeliveryLists = new ArrayList<>();
            if(chooesStash.size() > 0){
                sDeliveryLists =  delievryList.stream().filter(deli ->
                        (chooesStash.stream().map(SStashList::getFullPath).collect(Collectors.toList())).
                                contains(deli.getFullPath())).collect(Collectors.toList());
            }
            //批量修改本次投放申请中选择贮藏清单代码的来源状态
            if(sDeliveryLists.size() > 0){
                for (SDeliveryList deliList:sDeliveryLists){
                    deliList.setFromType(DeliveryListFromType.STASH);
                }
                updateBatchById(sDeliveryLists);
            }
        }
        //保存与贮藏清单不重复的代码文件
        List<SStashList> sstashLists = new ArrayList<>();
        //循环这次整理出来没有选择的代码文件
        no:
        for (SStashList stash:stashLists) {
            stash.setGuidWorkitem(guidWorkitem);
            //循环贮藏清单
            for (SStashList stashList:sStashLists) {
                if(stash.getFullPath().equals(stashList.getFullPath())){
                    continue no;
                }
            }
            sstashLists.add(stash);
        }
        if(sstashLists.size() > 0){
            //添加这次未选择的代码文件到贮藏清单中
            stashListService.insertBatch(sstashLists);
        }
    }

    /**
     * 根据文件名查询当前正在修改的该文件的工作项等信息
     * @param fileName
     * @return
     */

   public List<FileUsedList> selectListByFileName(String fileName) {
        return  this.baseMapper.selectListByFileName(fileName);
    }

    /**
     *
     * @param requestq
     * @return
     */
    @Override
    public List<FileUsedList>  selectListByFileName(DeliveryListSelectRequest requestq){
       // List<FileUsedList> resultList = new ArrayList<>();

        List<FileUsedList> fileList = new ArrayList<FileUsedList>();
        //文件名
        String fileName = requestq.getFileName();
        //工作项guid
        String wkItem = requestq.getGuidWorkItem();
        //环境guid
        String pro = requestq.getGuidProfiles();
        //是否查询已经投产的工作项:0-是,1-否
        String flag =  requestq.getSelectFlag();

        List<String> proList = new ArrayList<String>();
        List<FileUsedList> wkList = new ArrayList<FileUsedList>();

        if(null != pro){
            //根据环境查询
            proList = selectByProfilesNO(pro);
        }

        if (proList.size() > 0 ){
            wkList = selectByWorkItem(proList);
        }else if(null != wkItem){
            proList.add(wkItem);
            wkList = selectByWorkItem(proList);
        }

        //根据文件查询
        if( wkList.size() > 0 ){
            fileList = selectByFullPath(keepSameProfiles(wkList,pro),flag,pro);
        }else if(null != fileName){
            FileUsedList file = new FileUsedList();
            file.setFullPath(fileName);
            file.setGuid(0);
            wkList.add(file);
            fileList =  selectByFullPath(keepSameProfiles(wkList,pro),flag,pro);
        }
        return keepOlnyPro( fileList , pro);
    }

    /**
     * 已知环境的情况下保持值显示一个环境
     *
     * @param fileList
     * @param pro
     * @return
     */
   public List keepOlnyPro( List<FileUsedList> fileList ,String pro){
        List list = new ArrayList();
        if(fileList.size() > 0 && !"".equals(pro) && null != pro){
            for (FileUsedList file1:fileList
                 ) {
                FileUsedList file  = new FileUsedList();
                List<FileUsedList> list1 = file1.getList();
                if(list1.size() > 0 ) {
                    List list2 = new ArrayList();
                    for (FileUsedList file2 : list1
                    ) {
                        String guidPro = file2.getGuidProfiles();
                          if (pro.equals(guidPro)) {
                            list2.add(file2);
                        }
                    }
                    file1.setList(list2);
                }
                list.add(file1);
            }
        }else{
            list = fileList;
        }
        return list;
   }
    /**
     * 当环境不为空时去除wkList对象中不同的环境数据
     * @param wkList
     * @param pro
     * @return
     */
    public List keepSameProfiles(List<FileUsedList> wkList,String pro){

        List<FileUsedList> list = new ArrayList<FileUsedList>();
        if(null != pro && "" != pro && wkList.size() > 0 ){
            for(int i = 0 ; i < wkList.size() ; i++){
                String profiles = wkList.get(i).getGuidProfiles();
                if( pro.equals( profiles) ){
                    list.add(wkList.get(i));
                }
            }
        }else{
            list = wkList;
        }
        return list;
    }

    /**
     * 保持最终结果中所有的文件都是同一个环境中的
     * @return
     */
    public List keepSameFile(List<FileUsedList> fileList,String pro){
        List resultList = new ArrayList();
        if(fileList.size() > 0){
            //结果集的第一层
            for(int i = 0 ; i < fileList.size(); i++ ){
                FileUsedList resultFlie = new FileUsedList();
                List list = fileList.get(i).getList();
                if(list.size() > 0){
                    List list2 = new ArrayList();
                    //结果集的第二层
                    for(int m = 0 ; m <list.size();m++ ){
                        FileUsedList file = (FileUsedList)list.get(m);
                        //保留相同环境的

                        String profile = file.getGuidProfiles();

                        if(pro.equals(profile)){
                            list2.add(file);
                        }
                    }
                    resultFlie.setList(list2);
                }
                resultList.add(resultFlie);
            }
        }
        return resultList;
    }


    /**
     * 去除将要查询的文件中的重复内容
     * @param list
     * @return
     */
    public List setValue(List <FileUsedList> list){
        List <FileUsedList> list2 = new ArrayList<FileUsedList>();
        if(list.size() > 0 ){
            for(int n = 0 ; n < list.size() ;n++ ){
                if(list2.size() > 0 ){
                    for(int m = 0 ; m < list2.size() ; m++ ){
                        if(!list2.get(m).getFullPath().contains(list.get(n).getFullPath())){
                            list2.add(list.get(n));
                        }
                    }
                }else{
                    list2.add(list.get(n));
                }
            }
        }
        return  list2;
    }
    /**
     *
     * @param fullPath
     * @return
     */
    public  List<FileUsedList> selectByFullPath( List<FileUsedList> fullPath,String flag,String pro){
        List<FileUsedList> resultList = new ArrayList<FileUsedList>();

        if(fullPath.size() > 0 ){
            for(int m = 0 ; m  < fullPath.size() ; m++){
                Set<FileUsedList> set = new HashSet();
                List<FileUsedList> fileList1 = selectListByFileName( fullPath.get(m).getFullPath());
                set.addAll(fileList1);
                List<FileUsedList> fileList =  new ArrayList<>(set);

                if(fileList.size() > 0){ if(null != pro && "" != pro){
                        for (int n = 0 ;n < fileList.size() ; n++){
                            //如果查询到的文件的工作项等于传入的工作项，去除该查询结果
                            if(pro.equals(fileList.get(n).getGuidWorkitem())){
                                fileList.remove(n);
                            }
                        }
                    }
                    if("1".equals(flag) ){
                        for(int i = 0 ;i < fileList.size() ; i++){
                            //item_status = 1 ,为已经投产的代码
                            if("1".equals(fileList.get(i).getItemStatus()) ){
                                fileList.remove(i);
                            }
                        }
                    }
                }

                if(fileList.size() > 1){
                        FileUsedList fileUsed = new FileUsedList();

                        //做为查询条件的文件名
                        fileUsed.setFullPath(fullPath.get(m).getFullPath());
                        //作为查询条件的文件的guid
                        Integer id = fullPath.get(m).getGuid();
                        if(null != id ){
                            fileUsed.setGuid (id);
                        }
                        //查询结果
                        fileUsed.setList(fileList);
                        resultList.add(fileUsed);
                }
            }
        }
        return resultList ;
    }
    /**
     * 根据工作项查询文件,并将工作项
     * @param workItemGuid
     * @return
     */

    public List<FileUsedList> selectByWorkItem(List<String> workItemGuid) {
        List<FileUsedList> wotkItemList = new ArrayList<FileUsedList>();

        List<FileUsedList> pathList = new ArrayList<FileUsedList>();
        if (workItemGuid.size() > 0) {
            for (int i = 0; i < workItemGuid.size(); i++) {
                if (null != workItemGuid.get(i)) {
                    wotkItemList = selectListByWorkItem(workItemGuid.get(i));
                }
                if (wotkItemList.size() > 0) {
                    for (int j = 0; j < wotkItemList.size(); j++) {
                        FileUsedList file = new FileUsedList();
                        file.setFullPath(wotkItemList.get(j).getFullPath());
                        file.setGuid(wotkItemList.get(j).getGuid());
                        file.setGuidProfiles(wotkItemList.get(j).getGuidProfiles());
                        pathList.add(file);
                    }
                }
            }
        }
        return pathList;
    }

    public List<String > selectByProfilesNO (String profiles ){

        List workItemList = new ArrayList();
        List<FileUsedList> list = this.baseMapper.selectListByProfiles( profiles );
        if( list.size() > 0 ){
            for(int i = 0 ; i < list.size() ; i++ ){
                String workItem =  list.get(i).getGuidWorkitem();
                workItemList.add(workItem);
            }
        }
        return  workItemList;
    }
    @Override
    public List<FileUsedList> selectListByWorkItem(String guidWrkItem){
        return this.baseMapper.selectListByWorkItem(guidWrkItem);
    }
    @Override
    public List<FileUsedList> selectListByProfiles(String guidProfiles){
        return this.baseMapper.selectListByProfiles( guidProfiles );
    }
}

